#!../../jsrun

var count = 0;

var get_counter = function() {
	return count++;
};

(function() {
	var objects = [];
	for (var i = 0; i < 100; ++i)
		objects[objects.length] = [
			'obj' + i ,
			Math.round(600 * Math.random()),
			Math.round(600 * Math.random())
		];


	var index = {};
	for (var i = 0; i < objects.length; ++i)
		index[objects[i][0]] = objects[i];

/*
	var dot = {};
	for (var id,x,y,i = 0; i < objects.length; ++i) {
		x = objects[i][1];
		y = objects[i][2];
		x = Math.round(x / 10);
		y = Math.round(y / 10);
		id = 'dot_' + x + y;
		dot['dot_' + x + y] = objects[i];
	}
*/

	get_objects = function() {
		return objects;
	};
	
	setTimeout(function(){
		var max = objects.length;
		while (true) {
			var n = Math.floor(max * Math.random());
			for (var i = 0; i < n; ++i)
				objects[i][1] += 2;
			for (; i < max; ++i)
				objects[i][2] += 2;
			sleep(100);
		}
	});
	
	update_objects = function(xx){
		var i, j, x, y, id, obj;
		var idx = {};
		for (i in index)
			idx[i] = index[i];
		outer:
		for (i = 0; i < xx.length; ++i) {
			id = xx[i][0];
			obj = idx[id];
			x = xx[i][1];
			y = xx[i][2];
			var X = Math.round(x / 50);
			var Y = Math.round(y / 50);
			for (j = 0; j < objects.length; ++j) {
				if (objects[j][0] == id) continue;
				if (X == Math.round(objects[j][1] / 50) && Y == Math.round(objects[j][2] / 50))
					continue outer;
			}
			obj[1] = x;
			obj[2] = y;
		}
		var out = [];
		for (i in idx)
			out[out.length] = idx[i];
		return out;
	};
})();




var onjsonrequest = function(x) {
	var result;
	try {
		var method = this[x.method];
		result = method.call(this, x.params);
		return { error: false, result: result }
	} catch(e) {
		return { error: true, data: '' + e }
	}
};


var s = new Server;
s.port = 51234;
s.run();



while (true) sleep(1000000);



